var loginInfo; //登陆信息
Ext.BLANK_IMAGE_URL = '../jslib/ext-3.3.1/resources/images/default/s.gif';
Ext.onReady(function() {
	Ext.QuickTips.init();
	MyUtils.getJson('login!getLoginInfo.action', true, function(data){
		if (data.data){//已经登陆，进入主页面
			loginInfo = data.data;
			initMainLayout();
		}
		else{//未登陆，打开登陆窗口
			openLoginWin();
		}
	});
});

HeadPanel = {
        region: 'north',
        margins:'0 3 0 3',
        contentEl: 'header',
        autoHeight: true,
        border: false,
        margins: '0 0 5 0'
    };
MenuPanel = {
        region: 'west',
        collapsible: true,
        title: '系统菜单',
        xtype: 'treepanel',
        width: 150,
        margins:'0 0 3 3',
        autoScroll: true,
        split: true,
        loader: new Ext.tree.TreeLoader(),
        root: new Ext.tree.AsyncTreeNode({
            expanded: true,
            children: [{
                text: '书籍管理',
                url: 'book_mgr.html',
                leaf: true
            }, {
                text: '修改密码',
                leaf: true,
                fn: modifyPwd
            }, {
                text: '退出系统',
                leaf: true,
                fn: logout
            }]
        }),
        rootVisible: false,
        listeners: {
            click: function(n) {
            	if (n.attributes.modules){
            		ScriptMgr.load({
            			scripts:n.attributes.modules, 
            			callback: function(){}
            		});
            	}
            	else if (n.attributes.url){
            		openTab(n.attributes.text, n.attributes.url);
            	}
            	else if (n.attributes.fn){
            		n.attributes.fn.call();
            	}
            }
        }
    };

MainPanel = new Ext.TabPanel({
    region: 'center',
    margins:'0 3 3 0'
});

function initMainLayout(){
	new Ext.Viewport({
	    layout: 'border',
	    items: [HeadPanel, MenuPanel, MainPanel]
	});
	//MenuPanel.root.firstChild.select();
	MenuPanel.root.firstChild.fireEvent('click', MenuPanel.root.firstChild);
}

/**
 * 打开登陆窗口
 */
function openLoginWin(){
	//执行登陆的方法
	var doLogin = function(){
		var form = loginForm.getForm();
    	if (!form.isValid()){
    		return;
    	}
    	MyUtils.waitSubmitting();
    	form.submit({
    		//waitTitle: 'wait',
    		//waitMsg: '登陆中……',
            url:'login!login.action',
			success: function(form, action) {
				loginInfo = action.result.data;
    	    	loginWin.close();
    	    	initMainLayout();
			},
			failure: function(form, action) {
     	    	MyUtils.actionError(action, '登陆失败', userNameFocus);
			}
    	});
    };
    //设置焦点的方法
    var userNameFocus = function(){
    	loginForm.getForm().items.itemAt(0).focus(true, 100);//只用focus()不行
    };
    //登陆的表单
	var loginForm = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 50,
        labelPad: 5,
        labelSeparator: ":",
        labelAlign: "right",
        defaultType: 'textfield',
        items: [{
            fieldLabel: '用户名',
            name: 'username',
            allowBlank:false,
            anchor:'100%'
        },{
        	inputType: 'password',
            fieldLabel: '密码',
            name: 'password',
            allowBlank:false,
            anchor: '100%',
            listeners: {
                specialKey :function(field,e){
                    if (e.getKey() == Ext.EventObject.ENTER) {//按回车
                    	doLogin();
                    }
                }
            }
        }]
	});
	//登陆的窗口
	var loginWin = new Ext.Window({
        title: '登陆窗口',
        width: 250,
        height: 130,
        layout: 'fit',
        plain:true,
        modal: true,
        resizable: false,
        closable: false,
        bodyStyle:'padding:5px;',
        buttonAlign:'right',
        iconCls: 'icon-window',
        items: loginForm,
        listeners: {
        	show: userNameFocus //设置焦点
        },
        buttons: [{
            text: '登陆',
            iconCls: 'icon-login',
            handler: doLogin,
            scope: this
        },{
            text: '重置',
            handler: function(){this.getForm().reset();},
        	scope: this
        }]
    });
	loginWin.show();
}

/**
 * 退出登陆
 */
function logout(){
	Ext.Msg.confirm('提示', '确定要退出登陆吗？', function(result){
		if (result != 'yes') return;
		MyUtils.request('login!logout.action', true, function(){
			location.href = location.href;
		});
	});
}

function openTab(title, url){
	var tabsOpened = MainPanel.find("title", title);
	if (tabsOpened.length > 0){
		var tab = tabsOpened[0];
		MainPanel.setActiveTab(tab);
		var iframe = tab.getEl().query('iframe')[0];
		iframe.src = iframe.src;
		return;
	}
	var tab = MainPanel.add({
		title: title,
		html: '<iframe src="' + url + '" style="width:100%;height:100%;" frameborder="no"></iframe>',
		closable:true
	});
	tab.show();
	tab.focus();
}

function modifyPwd(){
	//保存方法
	var save = function(){
		var form = formPanel.getForm();
		if (MyUtils.formNotValid(form)) return;
    	if (form.findField("newPassword").getValue() != form.findField("retypePassword").getValue()){
    		MyUtils.alert("两次输入的密码不一样！");
    		return;
    	}
    	MyUtils.waitSubmitting();
    	form.submit({
            url:'login!changePassword.action',
			success: function(form, action) {
    	    	win.close();
        		MyUtils.hint("密码已修改！");
			}
    	});
    };
    //表单
	var formPanel = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 60,
        labelPad: 5,
        labelSeparator: ":",
        labelAlign: "right",
        defaultType: 'textfield',
        items: [{
        	inputType: 'password',fieldLabel: '新密码',
            name: 'newPassword',allowBlank:false,anchor:'100%'
        },{
        	inputType: 'password',fieldLabel: '密码确认',
            name: 'retypePassword',allowBlank:false,anchor: '100%',
            listeners: {
                specialKey :function(field,e){
                    if (e.getKey() == Ext.EventObject.ENTER) {//按回车
                    	save();
                    }
                }
            }
        }]
	});
	//窗口
	var win = new Ext.Window({
        title: '修改密码', width: 250, height: 130, layout: 'fit',
        plain:true, modal: true,
        bodyStyle:'padding:5px;', buttonAlign:'right', iconCls: 'icon-window',
        items: formPanel,
        listeners: {
        	show: function(){formPanel.getForm().items.itemAt(0).focus(true, 100)}
        },
        buttons: [{
            text: '确定', iconCls: 'icon-save', handler: save
        },{
            text: '取消', iconCls: 'icon-close', handler: function(){win.close();}
        }]
    });
	win.show();
}